package com.dragonfly.shutter.services;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.dragonfly.shutter.DAOs.AlbumDAO;
import com.dragonfly.shutter.DAOs.BrowseLogDAO;
import com.dragonfly.shutter.DAOs.FriendDAO;
import com.dragonfly.shutter.DAOs.UserDAO;
import com.dragonfly.shutter.beans.BrowseLog;
import com.dragonfly.shutter.beans.Friend;
import com.dragonfly.shutter.beans.UserBrief;
import com.dragonfly.shutter.beans.UserDetail;

/**
 * 用户中心服务类
 * @author 黄挺
 *
 */
public class UserService {
	private UserDAO userDAO;
	private BrowseLogDAO browseLogDAO;
	private AlbumDAO albumDAO;
	private FriendDAO friendDAO;

	/**
	 * 用户中心服务函数
	 * @param userID 用户ID
	 * @param requestUrl 请求URL
	 * @return 用户详细Bean
	 * @throws Exception 用户不存在或者用户未激活
	 */
	public UserDetail doService(Integer userID, String requestUrl) throws Exception{
		//生成浏览信息
		BrowseLog browseLog = new BrowseLog();
		if(userID != null )
			browseLog.setUserID(userID);
		browseLog.setBrowseTime(new Date(System.currentTimeMillis()));
		browseLog.setUrl(requestUrl);
		
		UserDetail userDetail = doDBOperate(userID, browseLog);
		
		return userDetail;
	}
	
	/**
	 * 用户中心数据操作类
	 * @param userID 用户ID
	 * @param browseLog 日志Bean
	 * @return 用户详细Bean
	 * @throws Exception
	 */
	public UserDetail doDBOperate(Integer userID, BrowseLog browseLog) throws Exception{
		UserDetail userDetail = userDAO.selectUserByUserId(userID);
		//不存在的用户
		if(userDetail == null )
			throw new Exception("不存在的用户");
		
		//未激活的用户
		if(userDetail.getFlagActive().toLowerCase().equals("notactived"))
			throw new Exception("用户尚未激活，请先激活");
		
		userDetail.setAlbums(albumDAO.selectPagedAlbumByUserID(userID, 0, 10));
		
		//获取用户好友
		List<Friend> friends = friendDAO.selectPagedFriendByUserID(userID, 0, 6);
		List<UserBrief> users = new ArrayList<UserBrief>();
		
		for(Friend friend : friends )
			users.add(friend.getFriend());
		
		userDetail.setFriends(users);
		
		browseLogDAO.insertBrowseLog(browseLog);
		return userDetail;
	}

	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}

	public void setBrowseLogDAO(BrowseLogDAO browseLogDAO) {
		this.browseLogDAO = browseLogDAO;
	}

	public void setAlbumDAO(AlbumDAO albumDAO) {
		this.albumDAO = albumDAO;
	}

	public void setFriendDAO(FriendDAO friendDAO) {
		this.friendDAO = friendDAO;
	}
}
